package com.ycfmedical.bed.ui.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineDataSet;
import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.R;
import com.ycfmedical.bed.listener.IvsReplaceData;
import com.ycfmedical.bed.model.ChartManage;
import com.ycfmedical.bed.present.VSPresenter;
import com.ycfmedical.bed.service.VitalSignService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.mvp.XFragment;


/**
 * Created by Administrator on 2017-04-05.
 */

public class VsFragment extends XFragment<VSPresenter> implements IvsReplaceData {

    @BindView(R.id.tab_heart)
    LineChart heartLineChart;               //心率
    @BindView(R.id.tab_breathe)
    LineChart breatheLineChart;             //呼吸
    @BindView(R.id.tab_temperature)
    LineChart temperatureLineChart;         //体温
    @BindView(R.id.tab_sleep)
    LineChart sleepLineChart;               //睡眠

    @BindView(R.id.text_heart)
    TextView heart;                         //心率
    @BindView(R.id.text_temperature)
    TextView Temperature_data;              //呼吸
    @BindView(R.id.text_breathe)
    TextView breathe;                       //体温
    @BindView(R.id.text_Weight_data)
    TextView Weight_data;                   //体重


    @BindView(R.id.text_average_heart)
    TextView avHeart;                       //平均心率
    @BindView(R.id.text_average_breathe)
    TextView avBreathe;                     //平均呼吸

    @BindView(R.id.text_average_sleepTime)
    TextView avSleepTime;                   //平均睡眠时间

    @BindView(R.id.sleep_embed)             //深睡
    TextView sleepEmbed;
    @BindView(R.id.sleep_commonly)          //中睡
    TextView sleepCommonly;
    @BindView(R.id.sleep_badly)             //浅睡
    TextView sleepBadly;
    @BindView(R.id.sleep_sober)             //清醒
    TextView sleepSober;

    private ChartManage chartManage;        //图表管理类，用来设置图表样式
    private ArrayList<TextView> textViews;
    private VitalSignService.Mybinder mybinder;
    private Bundle bundle;
    private callBack callBack;
    private String[] mapData = new String[4];
    private String Time;
    private HashMap<String, TextView> texts;

    @Override
    public void initData(Bundle savedInstanceState) {
        init();
        callBack = (VsFragment.callBack) context;
    }

    private void init() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        Date curDate = new Date(System.currentTimeMillis());
        textViews = new ArrayList<TextView>();

        bundle = new Bundle();
        chartManage = new ChartManage();
        texts = new HashMap<String ,TextView>();
        texts.put("深睡",sleepEmbed);
        texts.put("中睡",sleepCommonly);
        texts.put("浅睡",sleepBadly);
        texts.put("清醒",sleepSober);

        chartManage.addChart(heartLineChart,false);
        chartManage.addChart(breatheLineChart,false);
        chartManage.addChart(temperatureLineChart,false);
        chartManage.addChart(sleepLineChart,false);
        sleepLineChart.setTouchEnabled(false);

        chartManage.setX(0, 0f, Constants.X_HEART_CONTENT, false);
        chartManage.setX(1, 0f, Constants.X_BREATHE_CONTENT, false);
        chartManage.setX(2, 0f, Constants.X_TEMPERATURE_CONTENT, false);
//        chartManage.setX(3, 0f, Constants.X_SLEEP_CONTENT, true);

        chartManage.setY(0, 0f, Constants.Y_HEART_CONTENT, false);
        chartManage.setY(1, 0f, Constants.Y_BREATHE_CONTENT, false);
        chartManage.setY(2, 0f, Constants.Y_TEMPERATURE_CONTENT, false);
        chartManage.getLineCharts().get(3).getAxisLeft().setEnabled(false);
        chartManage.getLineCharts().get(3).getAxisRight().setEnabled(false);
        chartManage.getLineCharts().get(3).getXAxis().setDrawGridLines(false);
//        chartManage.setY(3, 50f, Constants.Y_SLEEP_CONTENT, false);


//        chartManage.getLineCharts().get(3).getAxisLeft().setLabelCount(10);
//        chartManage.getLineCharts().get(3).getXAxis().setLabelCount(10);

        textViews.add(heart);
        textViews.add(breathe);
        Time = formatter.format(curDate);
        bundle.putString("time", Time);
        getP().showSleepData();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(context, VitalSignService.class);
        getActivity().getApplicationContext().bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        chartManage = null;
        mybinder.onUnbind();
        getActivity().getApplicationContext().unbindService(connection);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_vital_sign;
    }

    @Override
    public VSPresenter newP() {
        return new VSPresenter();
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ((VitalSignService.Mybinder) service).setIvsReplacedata(VsFragment.this);
            mybinder = (VitalSignService.Mybinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //Service被停止，回调的方法
        }
    };

    @Override
    public void replaceData(int content) {
        chartManage.getLineCharts().get(content).notifyDataSetChanged();
        chartManage.getLineCharts().get(content).invalidate();
    }

    @Override
    public void setServiceData(ArrayList<ArrayList<Entry>> lists) {
        //服务数据第一次更新专用方法
        chartManage.setLineData(lists);
        chartManage.setLine(0, Color.rgb(47, 201, 27), false, LineDataSet.Mode.CUBIC_BEZIER);
        chartManage.setLine(1, Color.rgb(27, 88, 201), false, LineDataSet.Mode.HORIZONTAL_BEZIER);
        chartManage.setLine(2, Color.rgb(209, 74, 25), false, LineDataSet.Mode.HORIZONTAL_BEZIER);
    }

    @Override
    public void setText(ArrayList<Float> data) {
        for (int i = 0; i < data.size(); i++) {
            textViews.get(i).setText(data.get(i) + "");
            mapData[i] = data.get(i) + "";
        }
        callBack.deliver(mapData);
    }

    @Override
    public void setText(int flag, String data) {
        switch (flag) {
            case Constants.BED_TEMPERATURE:
                Temperature_data.setText(data);
                break;
            case Constants.BED_WEIGHT:
                Weight_data.setText(data);
                if(data == null){
                    mapData[2] = "62";
                }else{
                    mapData[2] = data;
                }
                callBack.deliver(mapData);
                break;
            case Constants.BED_WIFE:
                    mapData[3] = data;
                    callBack.deliver(mapData);
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.layout_heart,
            R.id.layout_breathe,
            R.id.layout_temperature,
            R.id.btn_measureWeight,
            R.id.btn_measureTemperature,
            R.id.sleep_layout
    })
    public void onClick(View v) {
        FragmentTransaction fragmentTransaction;
        fragmentTransaction = getFragmentManager().beginTransaction();
        VsHistoryFragment vs_history = new VsHistoryFragment();
        VsmeasureFragment vs_measure = new VsmeasureFragment();
        switch (v.getId()) {
            case R.id.layout_heart:
                //心率
                bundle.putString("name", "心率");
                vs_history.setArguments(bundle);
                fragmentTransaction.replace(R.id.vs_home, vs_history);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case R.id.layout_breathe:
                //呼吸
                bundle.putString("name", "呼吸");
                vs_history.setArguments(bundle);
                fragmentTransaction.replace(R.id.vs_home, vs_history);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case R.id.layout_temperature:
                //温度
                bundle.putString("name", "温度");
                vs_history.setArguments(bundle);
                fragmentTransaction.replace(R.id.vs_home, vs_history);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case R.id.sleep_layout:
                //睡眠
                bundle.putString("name", "睡眠");
                vs_history.setArguments(bundle);
                fragmentTransaction.replace(R.id.vs_home, vs_history);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case R.id.btn_measureWeight:
                //测体重
                bundle.putString("name", "BodyWeight");
                vs_measure.setArguments(bundle);
                fragmentTransaction.replace(R.id.vs_home, vs_measure);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case R.id.btn_measureTemperature:
                //测体温
                bundle.putString("name", "Temperature");
                vs_measure.setArguments(bundle);
                fragmentTransaction.replace(R.id.vs_home, vs_measure);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            default:
                break;
        }
    }

    public interface callBack {
        void deliver(String[] data);
    }

    public String getTime() {
        return Time;
    }

    public ChartManage getChartManage() {
        return chartManage;
    }

    public TextView getAvHeart() {
        return avHeart;
    }

    public TextView getAvBreathe() {
        return avBreathe;
    }

    public TextView getAvSleepTime() {
        return avSleepTime;
    }
    public HashMap<String, TextView> getTexts() {
        return texts;
    }
}
